//
//  ZDBUpdatePhoneViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/28.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBUpdatePhoneViewController.h"
#import "DJLoginEnterTextItemCell.h"
#import "TPKeyboardAvoidingTableView.h"
#import "DJLoginFooterActionView.h"

@interface ZDBUpdatePhoneViewController ()
<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)TPKeyboardAvoidingTableView * ks_TableView2;
@property(nonatomic,strong) NSMutableArray * modelsArry2;
@property(nonatomic,strong) DJLoginFooterActionView * footerView;
@property(nonatomic,strong) NSData * imageData;
@end

@implementation ZDBUpdatePhoneViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self step_UI];
    [self request_ImageCode];
}

-(void)step_UI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.ks_TableView2];
    [_ks_TableView2 registerNib:[UINib nibWithNibName:@"DJLoginEnterTextItemCell" bundle:nil]  forCellReuseIdentifier:@"DJLoginEnterTextItemCell"];
    
    UIView * headerV = [BBControl createViewWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    headerV.backgroundColor = [UIColor clearColor];
    _ks_TableView2.tableHeaderView = headerV;
    
    self.footerView = [[NSBundle mainBundle]loadNibNamed:@"DJLoginFooterActionView" owner:self options:nil].lastObject;
    self.footerView .frame =CGRectMake(0, 0, kScreenWidth, 250);
    self.footerView.fogetBtn.hidden = YES;
    [self.footerView.loginBtn setTitle:@"提 交" forState:0];
     _ks_TableView2.tableFooterView = self.footerView;
    self.footerView.loginbtnTopC.constant = 0;
 
    WEAKSELF
    [self.footerView.loginBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf UpdatePhoneRequest];
    }];
}

-(void)UpdatePhoneRequest{
      [self.view endEditing:YES];
    DJLoginEnterTextItemCell * phoneCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
       DJLoginEnterTextItemCell * pswCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
       DJLoginEnterTextItemCell * phoneCell2 = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
       DJLoginEnterTextItemCell * imageCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
       DJLoginEnterTextItemCell * codeCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
       
       if (kStringIsEmpty(phoneCell.textTF.text)) {
           [JMNotifyView showNotify:@"请输入正确的手机号" isSuccessful:NO];
           return;
       }
       if ([self  isMobileNumChack:phoneCell.textTF.text]==NO) {
           [JMNotifyView showNotify:@"请输入正确格式的手机号~" isSuccessful:NO];
            return;

       }

       if (kStringIsEmpty(pswCell.textTF.text)) {
           [JMNotifyView showNotify:@"请输入正确的密码" isSuccessful:NO];
           return;
       }
       
       if (kStringIsEmpty(phoneCell2.textTF.text)) {
             [JMNotifyView showNotify:@"请输入新的的手机号" isSuccessful:NO];
             return;
         }
         if ([self  isMobileNumChack:phoneCell2.textTF.text]==NO) {
             [JMNotifyView showNotify:@"请输入正确格式新手机号~" isSuccessful:NO];
              return;

         }
       
       
       if (kStringIsEmpty(imageCell.textTF.text)) {
                [JMNotifyView showNotify:@"请输入图形验证码" isSuccessful:NO];
                return;
       }

       if (kStringIsEmpty(codeCell.textTF.text)) {
               [JMNotifyView showNotify:@"请输入新手机验证码" isSuccessful:NO];
               return;
         }
       [self showLoadingAnimation];
       NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userInfo_updateTel"];
       NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
      [dicc setValue:phoneCell.textTF.text forKey:@"userName"];
      [dicc setValue:pswCell.textTF.text forKey:@"passWord"];
       [dicc setValue:phoneCell2.textTF.text forKey:@"newTel"];
       [dicc setValue:imageCell.textTF.text forKey:@"imageCode"];
       [dicc setValue:codeCell.textTF.text forKey:@"telCode"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST:url parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
           STRONGSELFFor(weakSelf)
            [self stopLoadingAnimation];
           if (statusCode ==0) {
               if (strongSelf.updetaInfoClickBlock) {
                               strongSelf.updetaInfoClickBlock(YES,phoneCell2.textTF.text);
                    }
                    [strongSelf.navigationController popViewControllerAnimated:YES];
               [JMNotifyView showNotify:@"手机号修改成功" isSuccessful:YES];
           }else{
               [JMNotifyView showNotify:message isSuccessful:NO];
           }
          
       } failure:^(id responseObject, NSError *error) {
            [self stopLoadingAnimation];
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
       }];
    

}
-(void)request_ImageCode{
    //commen_getImageCode
    WEAKSELF
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"commen_getImageCode"];
    [[SmileHttpTool sharedInstance] GET_Data:url parameters:nil origin:YES success:^(NSInteger statusCode, NSURLSessionDataTask *task, id responseObject) {
        STRONGSELFFor(weakSelf);
         //NSLog(@"commen_getImageCode----%@",responseObject);
        NSData * imageData = [NSData dataWithData:responseObject];
        strongSelf.imageData = imageData;
        [strongSelf.ks_TableView2 reloadData];

    } failure:^(id responseObject, NSError *error) {
      
    }];

    //[self infoHeaderImageAndNameMoreEdit];
}

#pragma  mark -----tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJLoginEnterTextItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DJLoginEnterTextItemCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self stupCell:cell atIndex:indexPath];
    return cell;
    
}

-(void)stupCell:(DJLoginEnterTextItemCell *)cell  atIndex:(NSIndexPath *)indexPath{
    cell.textTF.tag = indexPath.row;
      [cell.textTF addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
        
    switch (indexPath.row) {
        case 0:
        {
           // cell.textTF.text = @"musatest3";
            cell.textTF.placeholder = @"请输入原手机号";
            cell.iconImage.image = [UIImage imageNamed:@"login_user-1"];
           // [RestrictionInput restrictionInputTextField:cell.textTF maxNumber:10 showView:self.view showErrorMessage:@"用户名长度必须在6~10个字符"];
              cell.textTF.secureTextEntry = NO;
            cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
             [RestrictionInput restrictionInputTextField:cell.textTF maxNumber:11 showView:self.view showErrorMessage:@"用户名长度必须在6~10个字符"];
            NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#adadad"]}];
            cell.textTF .attributedPlaceholder = placeholderString;

        }
            break;
            
            case 1:
              {
                  cell.textTF.keyboardType = UIKeyboardTypeDefault;
                  NSDictionary * user_loginInfo = [kUserDefaults objectForKey:@"user_loginInfo"];
                  if (!kDictIsEmpty(user_loginInfo)) {
                               cell.textTF.text = [user_loginInfo jsonString:@"password"];
                           }
                   cell.textTF.placeholder = @"请输入密码";
                   cell.textTF.secureTextEntry = YES;
                  NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                  cell.textTF .attributedPlaceholder = placeholderString;
                  cell.iconImage.image = [UIImage imageNamed:@"login_icon_10"];
              }
                  break;
            case 2:
                {
                    cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
                   // cell.textTF.text = @"musatest3";
                    cell.textTF.placeholder = @"请输入新手机号";
                    cell.iconImage.image = [UIImage imageNamed:@"login_user-1"];
                    [RestrictionInput restrictionInputTextField:cell.textTF maxNumber:11 showView:self.view showErrorMessage:@"用户名长度必须在6~10个字符"];
                      cell.textTF.secureTextEntry = NO;
                    NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入新手机号" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#adadad"]}];
                    cell.textTF .attributedPlaceholder = placeholderString;
                   
                }
                    break;
            
            case 3:
            {
                cell.textTF.keyboardType = UIKeyboardTypeDefault;
                cell.textTF.placeholder = @"请输入图形验证码";
                cell.codeImage.hidden = NO;
                cell.anginBtn.hidden = NO;
                NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入图形验证码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                cell.textTF .attributedPlaceholder = placeholderString;
                cell.iconImage.image = [UIImage imageNamed:@"txyzm"];
                if (self.imageData) {
                             cell.codeImage.image = [UIImage imageWithData:self.imageData];
                    }
                         WEAKSELF
                    [cell.anginBtn add_BtnClickHandler:^(NSInteger tag) {
                             STRONGSELFFor(weakSelf);
                             [strongSelf request_ImageCode];
                    }];
                
            }
                break;
            case 4:
               {
                  cell.textTF.keyboardType = UIKeyboardTypeNumberPad;
                  cell.textTF.placeholder = @"请输入手机验证码";
                   cell.codeBtn.hidden = NO;
                   NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入手机验证码" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
                   cell.textTF .attributedPlaceholder = placeholderString;
                   cell.iconImage.image = [UIImage imageNamed:@"login_yzm"];
                   WEAKSELF
                        [cell.codeBtn add_BtnClickHandler:^(NSInteger tag) {
                            STRONGSELFFor(weakSelf);
                            [strongSelf phoneCode_ActionRequest:cell.codeBtn];
                        }];
               }
                   break;
        default:
            break;
    }

}


-(void)changedTextField:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
        {
               [RestrictionInput restrictionInputTextField:textField maxNumber:11 showView:self.view showErrorMessage:@"0~12字符~"];
        }
            break;
            case 1:
                  {
                      [RestrictionInput restrictionInputTextField:textField maxNumber:12 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 2:
                  {
                       [RestrictionInput restrictionInputTextField:textField maxNumber:11 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 3:
                  {
                      [RestrictionInput restrictionInputTextField:textField maxNumber:6 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;
            case 4:
                          {
                              [RestrictionInput restrictionInputTextField:textField maxNumber:6 showView:self.view showErrorMessage:@"0~12字符~"];
                          }
                              break;
            
        default:
            break;
    }
 
}


-(void)phoneCode_ActionRequest:(UIButton *)sender{
    
     DJLoginEnterTextItemCell * phoneCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
     DJLoginEnterTextItemCell * imageCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
     
     if (kStringIsEmpty(phoneCell.textTF.text)) {
         [JMNotifyView showNotify:@"请输入新的手机号" isSuccessful:NO];
         return;
     }
     if ([self  isMobileNumChack:phoneCell.textTF.text]==NO) {
         [JMNotifyView showNotify:@"请输入正确格式的新手机号~" isSuccessful:NO];
          return;
         
     }
     
     if (kStringIsEmpty(imageCell.textTF.text)) {
         [JMNotifyView showNotify:@"请输入图形验证码" isSuccessful:NO];
         return;
     }

     NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCode_SendMsgMobileAction"];
     NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
     [dicc setValue:phoneCell.textTF.text forKey:@"tel"];
     [dicc setValue:imageCell.textTF.text forKey:@"imageCode"];
     
   //  WEAKSELF
     [[SmileHttpTool sharedInstance] POST:url parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         if (statusCode ==0) {
                   dispatch_async(dispatch_get_main_queue(), ^{
                        [sender scheduledTimerWithTimeInterval:60.0f title:@"重新获取" countDownTitle:@"s" titleBackgroundColor:MAINCOLOR countDownTitleBackgroundColor:[UIColor lightGrayColor]];
                             [JMNotifyView showNotify:@"手机验证码已发送,注意查收" isSuccessful:YES];

                         });
         }else{
              [JMNotifyView showNotify:message isSuccessful:NO];
         }
     } failure:^(id responseObject, NSError *error) {
         [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
     }];
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[self dismissViewControllerAnimated:YES completion:nil];

}


#pragma mark ------setter   ---getter
-(TPKeyboardAvoidingTableView*)ks_TableView2
{
    if (_ks_TableView2==nil) {
        _ks_TableView2=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _ks_TableView2.separatorColor=[UIColor clearColor];
        _ks_TableView2.delegate=self;
        _ks_TableView2.backgroundColor = [UIColor clearColor];
        _ks_TableView2.dataSource=self;
        _ks_TableView2.sectionFooterHeight=0.01;
        _ks_TableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _ks_TableView2.estimatedRowHeight =0;
            _ks_TableView2.estimatedSectionHeaderHeight =0;
            _ks_TableView2.estimatedSectionFooterHeight =0;
            _ks_TableView2.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    return _ks_TableView2;
}

-(BOOL)isMobileNumChack:(NSString *)input{
    
    input = [input stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (input.length != 11) {
        return NO;
    } else {
        
        //^((13[0-9])|(14[1]|[4-9])|(15([0-3]|[5-9]))|(16[2]|[5-7])|(17[0-3]|[5-8])|(18[0-9])|(19[1|8|9]))\\d{8}$
        
        NSString * CT = @"^1[3|4|5|6|7|8|9][0-9]{9}$";
        NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
        BOOL res4 = [regextestct evaluateWithObject:input];
        if (res4 ) {
            return YES;
        }else {
            return NO;
        }
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
